# Alparslan Sari                 December 2012
# asari@udel.edu
# 2bit direct decoding
# Compression ration is 4:1
# Left over bits will represented in file name.

import os
import sys
import time
import array

def get_2bit(ele):
    if ele == '00':
        return 'A'
    elif ele == '01':
        return 'T'
    elif ele == '11':
        return 'G'
    else:
        return 'C'
    
def read_file(filename):
    f = open(filename, "rb")
    bwindow = []
    byte = 0
    try:
        while byte != "":
            byte = f.read(1)
            if len(byte) > 0:
                byte = ord(byte)
                byte = bin(byte)[2:].rjust(8, '0')
                bwindow.append(byte)
    finally:
        f.close()
    return bwindow

def convert(incd):
    bwindow = ""
    mdata = []
    for byte in incd:
        for bit in byte:
            bwindow = bwindow + str(bit)
        mdata.append(get_2bit(bwindow[0:2]))
        mdata.append(get_2bit(bwindow[2:4]))
        mdata.append(get_2bit(bwindow[4:6]))
        mdata.append(get_2bit(bwindow[6:]))
        bwindow = ""
    return "".join(mdata)
        
        
start_time = time.time()
rfile = sys.argv[1]
data = read_file(rfile)
#print data
tdata = convert(data)
# OK: Parse the input file and extract left over bits
pos = rfile.rfind('.')
bext = rfile[pos:]
rfile = rfile[:pos]
pos = rfile.rfind('.')
lover = rfile[pos+1:]
rfile = rfile[:pos]

if len(lover) == 2:
    tdata = tdata + get_2bit(lover)
elif len(lover) == 4:
    tdata = tdata + get_2bit(lover[0:2]) + get_2bit(lover[2:4])
elif len(lover) == 6:
    tdata = tdata + get_2bit(lover[0:2]) + get_2bit(lover[2:4]) + get_2bit(lover[6:])

# OK: update data
# OK: create the uncompressed file with original name

text_file = open(rfile, "w")
text_file.write(tdata)
text_file.close()
print time.time() - start_time, "seconds"

